package com.carl.zlds.controller;

import com.carl.zlds.tool.exception.GlobalException;
import com.carl.zlds.interceptor.Const;
import com.carl.zlds.interceptor.UserContext;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

/**
 * @author carl
 */
public class BaseController {
    @Autowired
    protected HttpServletRequest httpServletRequest;

    public BaseController() {
    }

    protected UserContext getUserContext() {
        Object userContext = this.httpServletRequest.getAttribute(Const.REQUEST_ATTR_KEY_USER_CONTEXT);
        return userContext instanceof UserContext ? (UserContext) userContext : null;
    }

    protected Long getUserId() {
        Object userContext = this.httpServletRequest.getAttribute(Const.REQUEST_ATTR_KEY_USER_CONTEXT);
        if (userContext == null) {
            throw new GlobalException(GlobalException.ERROR_AUTH_FAIL, "auth fail");
        } else if (userContext instanceof UserContext) {
            return ((UserContext) userContext).getUserId();
        } else {
            throw new GlobalException(GlobalException.ERROR_AUTH_FAIL, "auth fail");
        }
    }
}
